import urllib2,urllib,re,xbmcplugin,xbmcgui,xbmc,os

rootDir = os.getcwd()
if rootDir[-1] == ';':rootDir = rootDir[0:-1]
imageDir = os.path.join(rootDir, 'resources', 'thumbnails') + '/'


def DisplayCategories():
	xbmcplugin.addSortMethod(int(sys.argv[1]), 0)
	addDir("Toppers", "http://www.dumpert.nl/toppers/", 1, imageDir + "toppers.png")
	addDir("Filmpjes", "http://www.dumpert.nl/filmpjes/", 1, imageDir + "filmpjes.png")
	addDir("Plaatjes", "http://www.dumpert.nl/plaatjes/", 1, imageDir + "plaatjes.png")
	addDir("Audio", "http://www.dumpert.nl/audio/", 1, imageDir + "audio.png")
                
                
def OpenPage(url):
	xbmcplugin.addSortMethod(int(sys.argv[1]), 0)	
	try:
		page = int(url[len(url)-2])
		print "ParsedInt: " + str(page)
	except:
		page = 0
		print "ParsedInt: " + str(page)
		pass        
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
	response = urllib2.urlopen(req)
	link=response.read()
	match=re.compile('<a class="item" href="(.+?)">..<img src="(.+?)" alt="(.+?)" title=".+?" width=".+?" height=".+?" />..<div class="info">...<h3>.+?</h3>...<div class="date">(.+?)</div>...<p>(.+?)</p>',re.DOTALL).findall(link)
	for url2,thumb,name,date,desc in match:
		playFile(name,url2,2,thumb, date,desc)
	if page == 0:
		addDir("Ouder", url + str(page+1) + '/', 1, imageDir + "ouder.png")
	else:
		addDir("Ouder", url[:(len(url)-2)] + str(page+1) + '/', 1, imageDir + "ouder.png")
               
 # Play video                       
def INDEX(url,name):
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')
    response = urllib2.urlopen(req)
    link=response.read()
    clean=re.sub('&','&',link)
    response.close()
    type = ""
    match=re.compile(r"var flashurl = '(.+?)';").findall(clean)
    if len(match) > 0:
    	print "Found video on page " + match[0]
    	type = "Video"
    else:
    	match=re.compile(r'<img src="(.+?)" onclick=".+?" alt=".+?" title=".+?" class="downscaled" />').findall(clean)
    	if len(match) > 0:
    		print "Found photo on page" + match[0]
    		type = "Photo"
    	else:
    		match=re.compile(r'<embed src=".+?\?file=(.+?)&config=.+?" wmode=".+?" width=".+?" height=".+?" name=".+?"').findall(clean)
    		if (len(match) > 0):
    			print "Found audio on page" + match[0]
    			type = "Audio"
    		else:
    			print "No match found."
    
    
    if type == "Video":
    	core_player = xbmc.PLAYER_CORE_MPLAYER
      	icon = "DefaultVideo.png"
    	listitem = xbmcgui.ListItem( name, iconImage=icon, thumbnailImage="")
    	listitem.setInfo( "video", { "Title": name } )
    	
    elif type == "Audio":
    	core_player = xbmc.PLAYER_CORE_MPLAYER
       	icon = "DefaultVideo.png"
      	listitem = xbmcgui.ListItem( name, iconImage=icon, thumbnailImage="")
       	listitem.setInfo( "music", { "Title": name } )

    elif type == "Photo":
    	core_player = xbmc.PLAYER_CORE_DVDPLAYER
       	icon = "DefaultVideo.png"
       	listitem = xbmcgui.ListItem( name, iconImage=icon, thumbnailImage=match[0])
       	listitem.setInfo( "pictures", { "Title": name } )

    xbmc.Player( core_player ).play( match[0], listitem )
	        
      
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param

      
def addLink(name,url,thumbnail):
        
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok

def addDir(name,url,mode,thumbnail):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name,iconImage="DefaultFolder.png", thumbnailImage=thumbnail)
        liz.setInfo( type="Video", infoLabels={ "Title": name ,  } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
def playFile(name,url,mode,thumbnail,date,desc):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name,iconImage="DefaultFolder.png", thumbnailImage=thumbnail)
        description = "Post datum: " + date + "\nOmschrijving: " + desc
        liz.setInfo( type="Video", infoLabels={ "Title": name, "Date": date ,"Plot":description, "PlotOutline": description} )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
        return ok

params=get_params()
url=None
name=None
mode=None
thumb=None
try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
print ("Mode: "+str(mode))
print ("URL: "+str(url))
print ("Name: "+str(name))

if mode==None or url==None or len(url)<1:
        print ("categories")
        DisplayCategories()
elif mode==1:
        print ("index of : "+url)
        OpenPage(url)
elif mode==2:
		print ("play of: " + url)
		INDEX(url,name)

xbmcplugin.endOfDirectory(int(sys.argv[1]))